package com.hr.service.impl;

import com.hr.dao.CommentsDao;
import com.hr.dao.NewsDao;
import com.hr.entity.Comments;
import com.hr.entity.News;
import com.hr.service.NewsService;
import com.hr.until.Constant;
import com.hr.until.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/*
    Created with IntelliJ IDEA.
    @author: wang sir
    Date: 2021/7/16
    Time: 16:07
    To change this template use File | Settings | File Templates.
    Description: 
 */
@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsDao newsDao;

    @Autowired
    private CommentsDao commentsDao;

    @Override
    public List<News> queryAllNews() {
        List<News> newsList = newsDao.getAllByOrderByNcreateDateDesc();
        return newsList;
    }

    @Override
    public List<News> queryNewsByTname(String tname) {
        return newsDao.getAllNewsByTname(tname);
    }

    @Override
    public List<News> queryNewsByTid(Long tid) {
        return newsDao.getAllByNtidOrderByNcreateDateDesc(tid);
    }

    @Override
    public News queryNewsByNid(Long nid) {
        News news = newsDao.getNewsByNid(nid);
        List<Comments> commentsList = commentsDao.getAllByCnidOrderByCcreateDateDesc(nid);
        news.setCommentsList(commentsList);
        return news;
    }

    @Override
    public PageUtil queryNewsByPage(int pageNo) {
        PageUtil page = new PageUtil();
        int count = newsDao.countAllBy();
        page.setTotalCount(count);
        page.setPageNo(pageNo);
        List<News> newsList = newsDao.getNewsByPage((page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());
        page.setNewsList(newsList);
        return page;
    }

    @Override
    public Page queryJpaPageNews(int pageNo) {
        PageRequest pageRequest = PageRequest.of(pageNo-1, Constant.PAGESIZE, Sort.by(Sort.Direction.DESC,"ncreateDate"));
        Page<News> newsPage = newsDao.findAll(pageRequest);
        return newsPage;
    }

    @Override
    public boolean isNewsExists(Long tid) {
        return newsDao.existsNewsByNtid(tid);
    }

    @Override
    public News addNews(News news) {
        news.setNcreateDate(new Date());
        return newsDao.save(news);
    }

    @Override
    public News updateNews(News news) {
        news.setNmodifyDate(new Date());
        return newsDao.save(news);
    }

    @Override
    @Transactional//支持事务
    public void deleteNewsById(Long nid) {
        commentsDao.deleteByCnid(nid);
        newsDao.deleteByNid(nid);
    }
}